package com.haojii.twittertranslate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

public class ExciteTranslate {
	
	private static final Logger log = Logger.getLogger(ExciteTranslate.class.getName());
	
	public static void main(String[] args)
	{
		String source = "ホテルに帰って来たよね。今日は一日長かった。癒されに来たはずが、アクティブに動き過ぎて疲れが溜まってしまった。このままじゃ荷物が多過ぎるよね";
		String translatedText = ExciteTranslate.translateJA2CH(source);
		System.out.println(translatedText);
		
	}
	/**
	 * @param args
	 */
	public static String translateJA2CH(String toBeTranslated) {
		String result = "";
		try {
		    String data = URLEncoder.encode("before", "UTF-8") + "=" + URLEncoder.encode(toBeTranslated, "UTF-8");
		    data += "&" + URLEncoder.encode("big5", "UTF-8") + "=" + URLEncoder.encode("no", "UTF-8");
		    data += "&" + URLEncoder.encode("start", "UTF-8") + "=" + URLEncoder.encode("翻译", "UTF-8");
		    data += "&" + URLEncoder.encode("wb_lp", "UTF-8") + "=" + URLEncoder.encode("JACH", "UTF-8");
		    
		    URL url = new URL("http://www.excite.co.jp/world/jiantizi/");
		    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
            connection.setDoOutput(true); 
            connection.setRequestMethod("POST"); 
            
		    OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
		    wr.write(data);
		    wr.flush();
		    
		    //if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
                // OK 
			    // Get the response
			    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			    String line;
			    while ((line = rd.readLine()) != null) {
			    	if(line.contains("<textarea cols=36 rows=15 name=\"after\" id=\"after\" wrap=\"virtual\""))
			    	{
			    		int fromIndex = line.indexOf(">");
			    		int endIndex = line.indexOf("</textarea>", fromIndex);
			    		result = line.subSequence(fromIndex+1, endIndex).toString();
			    		log.info(result);
			    		break;
			    	}
			        //System.out.println(line);
			    }
			    wr.close();
			    rd.close();
		    //}
		} catch (Exception e) {
			e.printStackTrace();
			log.warning("[Exception] happened during translateJA2CH:\n"+e.getMessage());
		}
		return result;
	}

}
